<template>
  <div>
    <el-dialog :visible.sync="isShow" @close="closeDialog" width="60%" :key="dialogKey">
      <!-- 自定义标题 -->
      <template #title>
        <div class="dialog-header">
          <span class="dialog-title">差旅报销</span>
          <div class="dialog-actions" v-if="isEditable">
            <el-button size="small" @click="closeDialog">取消</el-button>
            <el-button size="small" type="primary" @click="save">保存</el-button>
            <el-button size="small" type="primary" @click="submit">提交</el-button>
          </div>
        </div>
      </template>
      <!-- 差旅基本信息 -->
      <div class="section">
        <h2 class="section-header">差旅报销</h2>
        <el-form :model="travelForm" ref="ruleForm" label-width="100px" class="demo-ruleForm" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="单据序号" prop="travelId">
                <el-input v-model="travelForm.travelId" :readonly="true" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报销人" prop="ename">
                <el-input v-model="travelForm.ename" :readonly="true" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="出发时间" prop="startTime">
                <el-date-picker type="date" v-model="travelForm.startTime" style="width: 100%;" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" :readonly="true" :disabled="true"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="返回时间" prop="endTime">
                <el-date-picker type="date" v-model="travelForm.endTime" style="width: 100%;" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" :readonly="true" :disabled="true"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="天数" prop="days">
                <el-input v-model="travelForm.days" :readonly="true" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报销申请时间" prop="reimbursedTime">
                <el-date-picker type="date" v-model="travelForm.reimbursedTime" style="width: 100%;" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" :readonly="true" :disabled="true"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="报销金额" prop="money">
                <el-input v-model="travelForm.money" :readonly="true" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="大写" prop="moneyUpper">
                <el-input v-model="travelForm.moneyUpper" :readonly="true" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="出差事由" prop="reason">
                <el-input type="textarea" :rows="4" v-model="travelForm.reason" placeholder="请输入出差事由"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-input v-model="travelForm.empno" type="hidden"></el-input>
        </el-form>
      </div>


      <!-- 差旅车票信息 -->
      <div class="section">
        <h2 class="section-header">差旅车票信息</h2>
        <div class="button-group" v-if="isEditable">
          <el-button type="primary" @click="selectTicket">选择车票信息</el-button>
          <el-button type="primary" @click="clearTicket">清空</el-button>
        </div>

        <el-row justify="center">
          <el-col :span="20">
            <el-table ref="multipleTable" :data="selectedTickets" tooltip-effect="dark"
              style="width: 100%; margin-left: auto;" border stripe>
              <el-table-column type="selection" width="50" align="center"></el-table-column>
              <el-table-column label="序号" min-width="50" align="center">
                <template slot-scope="scope">{{ scope.row.ticketId }}</template>
              </el-table-column>
              <el-table-column label="起始时间" min-width="150" align="center">
                <template slot-scope="scope">{{ scope.row.startTime }}</template>
              </el-table-column>
              <el-table-column label="到达时间" min-width="150" align="center">
                <template slot-scope="scope">{{ scope.row.endTime }}</template>
              </el-table-column>
              <el-table-column label="出发地" min-width="60" align="center">
                <template slot-scope="scope">{{ scope.row.departure }}</template>
              </el-table-column>
              <el-table-column label="到达地" min-width="60" align="center">
                <template slot-scope="scope">{{ scope.row.arrival }}</template>
              </el-table-column>
              <el-table-column label="出行类型" min-width="70" align="center">
                <template slot-scope="scope">{{ scope.row.way }}</template>
              </el-table-column>
              <el-table-column label="交通工具" min-width="70" align="center">
                <template slot-scope="scope">{{ scope.row.type }}</template>
              </el-table-column>
              <el-table-column label="金额" min-width="60" align="center">
                <template slot-scope="scope">{{ scope.row.price }}</template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>



      <!-- 差旅补助信息 -->
      <div class="section">
        <h2 class="section-header">差旅补助信息</h2>
        <div class="button-group">
          <el-button type="primary" @click="calculateAllowance" v-if="isEditable">计算补助</el-button>
        </div>

        <el-row justify="center">
          <el-col :span="20">
            <el-table ref="multipleTable" :data="allowanceList" tooltip-effect="dark" style="width: 100%;" border
              stripe>
              <el-table-column label="起始时间" min-width="150" align="center">
                <template slot-scope="scope">{{ scope.row.startTime }}</template>
              </el-table-column>
              <el-table-column label="结束时间" min-width="150" align="center">
                <template slot-scope="scope">{{ scope.row.endTime }}</template>
              </el-table-column>
              <el-table-column label="补助天数" min-width="150" align="center">
                <template slot-scope="scope">{{ scope.row.type }}</template>
              </el-table-column>
              <el-table-column label="补助金额" min-width="150" align="center">
                <template slot-scope="scope">{{ scope.row.price }}</template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>


      <!-- 审批意见 -->
      <div class="section">
        <h2 class="section-header">审批意见</h2>
        <el-card class="approval-info">
          <el-form :model="travelForm" label-width="100px" class="demo-ruleForm">
            <el-row>
              <!-- 部门经理意见 -->
              <el-col :span="12">
                <el-form-item label="部门经理意见" prop="managerOpinion">
                  <el-input type="textarea" v-model="travelForm.managerOpinion" :readonly="!isManagerRole"
                    placeholder="请输入部门经理意见" rows="4"></el-input>
                </el-form-item>
              </el-col>

              <!-- 总经理意见 -->
              <el-col :span="12">
                <el-form-item label="总经理意见" prop="directorOpinion">
                  <el-input type="textarea" v-model="travelForm.directorOpinion" :readonly="!isDirectorRole"
                    placeholder="请输入总经理意见" rows="4"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 操作按钮 -->
            <el-row>
              <el-col :span="24" style="text-align: right; margin-top: 10px;">
                <template v-if="isManagerRole || isDirectorRole">
                  <el-button type="warning" @click="reject"
                    v-if="isManagerApproval && isManagerRole || isDirectorApproval && isDirectorRole">驳回</el-button>
                  <el-button type="primary" @click="approve"
                    v-if="isManagerApproval && isManagerRole || isDirectorApproval && isDirectorRole">通过</el-button>
                  <el-button size="small" @click="closeDialog">取消</el-button>
                </template>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </el-dialog>

    <el-dialog title="选择车票信息" :visible.sync="showTicketDialog" width="70%" append-to-body>
      <ticket-choose @confirm="handleTicketsSelected" :travel-id="travelForm.travelId" :empno="travelForm.empno"
        :selectedTicketsFromParent="selectedTickets" />

    </el-dialog>


  </div>
</template>

<script>
import TicketChoose from './TicketChoose.vue';

export default {
  name: 'travelInfo',
  components: { TicketChoose },
  props: {
    isShow: Boolean,
    travelData: Array,
    travelInfo: Object,
  },
  computed: {
    // 判断是否为审批角色
    isManagerRole() {
      const roleIdsStr = localStorage.getItem('roleid');
      if (!roleIdsStr) return false;
      const roleIds = roleIdsStr.split(',').map(id => Number(id));
      return roleIds.includes(3);
    },
    isDirectorRole() {
      const roleIdsStr = localStorage.getItem('roleid');
      if (!roleIdsStr) return false;
      const roleIds = roleIdsStr.split(',').map(id => Number(id));
      return roleIds.includes(2);
    },
    isManagerApproval() {
      return this.travelForm.approval === 1;
    },
    isDirectorApproval() {
      return this.travelForm.approval === 2;
    },
    isEditable() {
      return this.travelForm.approval === 0;
    }
  },
  data() {
    return {
      dialogKey: 0,
      showTicketDialog: false,
      status: 0, // 当前审批状态
      travelForm: {
        id: 0,
        travelId: 0, // 自动生成travelId,
        empno: localStorage.getItem('empno'),
        ename: localStorage.getItem('ename'),
        roleid: '',
        startTime: '',
        endTime: '',
        days: '',
        money: '',
        moneyUpper: '',
        reason: '',
        reimbursedTime: '',
        approval: 0, // 0: 未提交或驳回, 1: 部门经理审批, 2: 总经理审批, 3: 审批完成
        managerOpinion: '',
        directorOpinion: '',
      },
      rules: {
        startTime: [{ required: true, message: '请选择出发时间', trigger: 'blur' }],
        endTime: [{ required: true, message: '请选择返回时间', trigger: 'blur' }],
        reason: [{ required: true, message: '请输入出差事由', trigger: 'blur' }],
        money: [{ required: true, message: '请计算报销金额', trigger: 'blur' }],
      },
      selectedTickets: [],
      allowanceList: [],
      approvalForm: {
        managerOpinion: '',
        directorOpinion: ''
      },
      total: 0
    };
  },
  methods: {
    handleTicketsSelected(tickets) {
      this.selectedTickets = tickets;
      this.showTicketDialog = false;
      // 调用接口计算出差时间
      this.calculateTravelTime(this.selectedTickets)
    },


    calculateTravelTime(tickets) {
      if (tickets.length === 0) {
        this.$message.warn('未选择车票');
      }
      if (tickets.length > 0) {
        this.$http.post('/getTravelTime', tickets).then(res => {
          if (res.status === 200) {
            const travelTime = res.data;
            const startDate = tickets[0].startTime;
            const endDate = tickets[tickets.length - 1].endTime;

            this.travelForm.startTime = startDate;
            this.travelForm.endTime = endDate;
            this.travelForm.days = travelTime;

            const dailyAllowance = 200;
            const totalAllowance = travelTime * dailyAllowance;

            // 生成补助列表
            this.allowanceList = [
              {
                startTime: startDate,
                endTime: endDate,
                type: travelTime,
                price: totalAllowance
              }
            ];
            this.calculateAllowance();
          } else {
            this.$message.error('获取出差时间失败');
          }
        }).catch(() => {
          this.$message.error('请求失败，请稍后再试');
        });
      }
    },
    closeDialog() {
      this.resetForm();
      this.$emit('closeDialog');
      this.$emit('setTravelInfo', null);
      if (!this.travelForm.travelId) {
        this.travelInfo = {};  // 如果是新增，清空传入的差旅信息
      }
    },


    resetForm() {
      this.travelForm.reimbursedTime = new Date()
      .toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })
      .replace(/\//g, '-');

      // 重置表单
      this.travelForm = {
        id: '',
        travelId: 0,
        empno: localStorage.getItem('empno'),
        ename: localStorage.getItem('ename'),
        startTime: '',
        endTime: '',
        days: '',
        money: '',
        moneyUpper: '',
        reason: '',
        reimbursedTime: this.travelForm.reimbursedTime,
        approval: 0,
        managerOpinion: '',
        directorOpinion: ''
      };

      this.selectedTickets = [];
      this.ticketList = [];
      this.allowanceList = [];
      this.total = 0;
      this.approvalForm = {
        managerOpinion: '',
        directorOpinion: ''
      };
      if (this.$refs['ruleForm']) {
        this.$refs['ruleForm'].resetFields();
      }
    },

    // 生成travelId的方法
    generateTravelId() {
      const empno = localStorage.getItem('empno');
      if (!empno || isNaN(Number(empno))) {
        console.error('员工工号无效，无法生成travelId');
        return '0'; // 工号无效时返回默认值
      }

      // 获取当前时间并格式化为 年月日时分秒（无分隔符）
      const now = new Date();
      const year = String(now.getFullYear()).slice(-2);
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hour = String(now.getHours()).padStart(2, '0');
      const minute = String(now.getMinutes()).padStart(2, '0');
      const second = String(now.getSeconds()).padStart(2, '0');
      // 拼接格式：empno+年月日时分秒
      return empno + year + month + day + hour + minute + second;
    },


    save() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (!valid) return;
        this.travelForm.approval = 0;
        let payload = {
          ...this.travelForm,
          tickets: this.selectedTickets
        };
        let isNew = !this.travelForm.travelId || this.travelForm.travelId === 0; // 判断是否新增
        if (isNew) {
          delete payload.travelId; // 新增时去掉travelId
        }
        let url = isNew ? '/insertTravel' : '/updateTravel';
          if (!isNew) {
          }
          // 保存差旅单信息
          await this.$http.post(url, payload).then(res => {
            if (res.data || res.status === 200) {
              // 新增时从返回值中取出新生成的 travelId
              if (isNew && res.data.travelId) {
                this.travelForm.travelId = res.data.travelId;
              }
              this.$message.success('保存成功');
              this.$emit('travelSave', res.data);
            } else {
              this.$message.error('保存失败');
            }
          });
      });
    },


    submit() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (!valid) return;
        this.travelForm.approval = 1;
        let payload = {
          ...this.travelForm,
          tickets: this.selectedTickets
        };
        console.log(payload.tickets);
        console.log(this.selectedTickets)
        let isNew = !this.travelForm.travelId || this.travelForm.travelId === 0; // 判断是否新增
        let url = isNew ? '/insertTravel' : '/updateTravel';
          // 保存差旅单信息
          await this.$http.post(url, payload).then(res => {
            if (res.data || res.status === 200) {
              // 新增时从返回值中取出新生成的 travelId
              if (isNew && res.data.travelId) {
                this.travelForm.travelId = res.data.travelId;
              }
              this.$message.success('保存成功');
              this.$emit('travelSave', res.data);
            } else {
              this.$message.error('保存失败');
            }
          });
      });
    },

    selectTicket() {
      // 打开前同步当前已选车票（用于自动勾选）
      if (!this.selectedTickets) this.selectedTickets = [];
      this.showTicketDialog = true;
    },


    clearTicket() {
      this.selectedTickets = [];

      // 重置与车票相关的表单字段
      this.travelForm.startTime = '';
      this.travelForm.endTime = '';
      this.travelForm.days = '';
      this.travelForm.money = '';
      this.travelForm.moneyUpper = '';

      // 清空补助列表
      this.allowanceList = [];

      // 重置总金额
      this.total = 0;
    },


    calculateAllowance() {
      if (this.selectedTickets.length === 0) {
        this.$message.warning('请先选择车票信息');
        return;
      }
      let TotalMoney = 0;
      this.selectedTickets.forEach(ticket => {
        let price = ticket.price;
        TotalMoney += price;
      })
      const allowanceTotal = this.allowanceList.length > 0 ? Number(this.allowanceList[0].price) : 0;
      const totalReimbursement = TotalMoney + allowanceTotal;
      this.travelForm.money = totalReimbursement;

      // 金额转大写
      this.travelForm.moneyUpper = this.$http.post('/moneyToChinese', { money: totalReimbursement }).then(res => {
        if (res.data && res.status === 200) {
          this.travelForm.moneyUpper = res.data; 
        } else {
          this.$message.error('金额转大写失败');
        }
      });
    },

    // 审批通过
    approve() {
      const travelId = this.travelForm.travelId;

      this.$confirm("确定要通过此差旅审批吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const approvalData = {
          travelId: travelId,
          ...(this.isManagerRole ? { managerOpinion: this.travelForm.managerOpinion } : {}),
          ...(this.isDirectorRole ? { directorOpinion: this.travelForm.directorOpinion } : {})
        };
        this.$http.post('/updateApprovalStatus1', approvalData).then(res => {
          if (res.data === true) {
            this.$message.success("审批已通过");
            this.$emit("stuSave", "success"); // 通知父组件刷新
            this.closeDialog();
          } else {
            this.$message.error("审批失败");
          }
        });
      }).catch(() => {
        this.$message.info("已取消操作");
      });

    },

    // 审批驳回
    reject() {
      const travelId = this.travelForm.travelId;
      let opinionEmpty = false;
      if (this.isManagerRole && this.isManagerApproval) {
        if (!this.travelForm.managerOpinion.trim()) {
          opinionEmpty = true;
        }
      } else if (this.isDirectorRole && this.isDirectorApproval) {
        if (!this.travelForm.directorOpinion.trim()) {
          opinionEmpty = true;
        }
      }
      //驳回时必须填写意见
      if (opinionEmpty) {
        this.$message.warning('驳回原因不能为空');
        return;
      }

      this.$confirm("确定要驳回此差旅申请吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const rejectionData = {
          travelId: travelId,
          ...(this.isManagerRole ? { managerOpinion: this.travelForm.managerOpinion } : {}),
          ...(this.isDirectorRole ? { directorOpinion: this.travelForm.directorOpinion } : {})
        };
        this.$http.post('/updateApprovalStatus2', rejectionData).then(res => {
          if (res.data === true || res.status === 200) {
            this.$message.warning("审批已驳回");
            this.$emit("stuSave", "success"); // 通知父组件刷新
            this.closeDialog();
          } else {
            this.$message.error("驳回失败");
          }
        });
      }).catch(() => {
        this.$message.info("已取消操作");
      });

    },


    fillFormData(info) {
      //获取当前时间
      this.travelForm.reimbursedTime = new Date()
      .toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })
      .replace(/\//g, '-');

      this.travelForm = {
        id: info.id || '',
        travelId: info.travelId || 0,
        empno: info.empno || localStorage.getItem('empno'),
        ename: info.empno || localStorage.getItem('ename'),
        startTime: info.startTime || '',
        endTime: info.endTime || '',
        days: info.days || '',
        money: info.money || '',
        moneyUpper: info.moneyUpper || '',
        reason: info.reason || '',
        reimbursedTime: info.reimbursedTime || this.travelForm.reimbursedTime,
        approval: info.approval || 0,
        managerOpinion: info.managerOpinion || '',
        directorOpinion: info.directorOpinion || ''
      };
      if (info.tickets) {
        this.selectedTickets = info.tickets;
        this.total = this.selectedTickets.length;
        // 自动计算天数与补助
        this.calculateTravelTime(this.selectedTickets);
      }
      else {
        this.selectedTickets = [];
        this.allowanceList = [];
      }
      if (info.empno) {
        this.$http.get('/getEnameByEmpno?empno=' + info.empno).then(res => {
          if (res.status === 200) {
            this.travelForm.ename = res.data;
          }
        });
      }
    },
  },
  
  watch: {
    // 监听对话框显示状态：打开时若为新增，强制重置
    isShow(newVal) {
      if (newVal && !this.travelInfo) { // 新增场景：对话框打开且无数据
        this.resetForm();
      } else if(newVal && this.travelInfo) {
        this.fillFormData(this.travelInfo);
      }
    }
  }

};
</script>


<style scoped>
.ticket-dialog .el-dialog__body {
  padding: 0;
}

.section {
  margin-bottom: 20px;
}

.button-group {
  text-align: right;
  margin-bottom: 10px;
}

.el-table {
  width: 80%;
  margin: 0 auto;
}


.section {
  margin-bottom: 20px;
}

.section-header {
  font-size: 18px;
  margin-bottom: 10px;
  text-align: left;
  /* 标题左对齐 */
}

.button-group {
  text-align: right;
  /* 按钮右对齐 */
  margin-bottom: 10px;
}

.el-row {
  margin-bottom: 10px;
}

.approval-info .hint {
  font-size: 12px;
  color: #999;
}

.el-table {
  width: 80%;
  /* 表格宽度适当缩减 */
  margin: 0 auto;
  /* 表格居中 */
}

.el-pagination {
  margin-top: 10px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  /* 左右分布 */
  align-items: center;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
}

.dialog-actions {
  display: flex;
  gap: 8px;
  /* 按钮间距 */
}
</style>
